package com.ltu.ai.sparkdesk.websocket.legal;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

import  com.ltu.util.exception.ApiException;

import lombok.extern.slf4j.Slf4j;



@Slf4j
public class TokenUtil {
	private static final IvParameterSpec iv = new IvParameterSpec(new byte[]{-66, 63, -57, 55, 49, -11, 107, -90, 19, -73, 56, -58, -55, -62, -84, -95});
	private static final String  CIPHER_MODEL = "AES/CBC/PKCS5Padding";
	private static final String  secret_key_MODEL = "AES";
	
	public static String getAuthToken(String appId, String appType,String keyStr) throws ApiException {
		if(StringUtils.isBlank(appId) || StringUtils.isBlank(appType))
		      throw  new ApiException("appId或appType必传");
		SecretKeySpec   key = new SecretKeySpec(keyStr.getBytes(), secret_key_MODEL);
		return encrypt(getToken(appId,appType),key);
	}
    /**
     * 加密
     */
    private static String encrypt(String plainText, SecretKeySpec key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_MODEL);
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
            return Base64.getUrlEncoder().withoutPadding().encodeToString(encryptedBytes);
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException |
                 NoSuchPaddingException | InvalidAlgorithmParameterException e) {
            log.error("生成 token 出错->{}", e.getMessage());
        }
        return null;
    }

    /**
     * 生成未加密的 token
     */
    private static String getToken(String appId, String appType) {
        return (System.currentTimeMillis() / 1000) + appId + appType;
    }
    
}

